<template>
  <div class="announcements-container">
    <h1 class="page-title">公告管理</h1>

    <!-- 添加公告按钮 -->
    <div class="actions">
      <el-button type="danger" @click="showAddDialog" class="add-btn">
        <el-icon><Plus /></el-icon>
        添加公告
      </el-button>
    </div>

    <!-- 公告表格 -->
    <el-table
      :data="announcementList"
      border
      style="width: 100%"
      class="announcement-table"
    >
      <el-table-column label="ID" width="80" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="140" />
      <el-table-column label="类型" width="120" align="center">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.types == '系统通知'
                ? 'success'
                : scope.row.types == '活动通知'
                ? 'warning'
                : scope.row.types == '功能更新'
                ? 'info'
                : scope.row.types == '流程变更'
                ? 'danger'
                : ''
            "
            effect="plain"
            size="small"
            class="type-tag"
          >
            {{ scope.row.types }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="dateTime"
        label="发布时间"
        sortable
        width="220"
        align="center"
      >
        <template #default="scope">
          {{ formatDate(scope.row.dateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.status === '已发布' ? 'success' : 'info'"
            effect="plain"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="warning"
            plain
            class="action-btn"
            @click="showUpDialog(scope.row)"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            plain
            class="action-btn"
            @click="del(scope.row)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="page"
        :page-size="size"
        :total="total"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        background
      />
    </div>

    <!-- 添加/编辑公告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑公告' : '添加公告'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="announcementForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
          />
        </el-form-item>
        <el-form-item label="类型" prop="types">
          <el-select
            v-model="announcementForm.types"
            placeholder="请选择公告类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in announcementTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="announcementForm.status">
            <el-radio :value="'已发布'" label="立即发布"></el-radio>
            <el-radio :value="'草稿'" label="保存为草稿"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="danger" @click="add">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { Edit, Delete, Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import {
  getAnnouncementList,
  updateAnnouncement,
  deleteAnnouncement,
  addAnnouncement,
} from "../../api/auth";


// 格式化日期时间函数
const formatDate = (date: string | Date): string => {
  if (!date) return "";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 公告接口
interface Announcement {
  _id?: string;
  title: string;
  content: string;
  types: string;
  dateTime: Date;
  status: string;
}

// 公告类型
const announcementTypes = [
  { label: "系统通知", value: "系统通知" },
  { label: "活动通知", value: "活动通知" },
  { label: "功能更新", value: "功能更新" },
  { label: "流程变更", value: "流程变更" },
];

// 表单校验规则
const formRules: FormRules = {
  title: [
    { required: true, message: "请输入公告标题", trigger: "blur" },
    { min: 2, max: 50, message: "长度应为2-15个字符", trigger: "blur" },
  ],
  types: [{ required: true, message: "请选择公告类型", trigger: "change" }],
  content: [
    { required: true, message: "请输入公告内容", trigger: "blur" },
    { min: 10, max: 500, message: "长度应为10-100个字符", trigger: "blur" },
  ],
};

// 状态变量
const announcementList = ref<Announcement[]>([]);
const page = ref<number>(1);
const size = ref<number>(10);
const total = ref<number>(0);
const dialogVisible = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const formRef = ref<FormInstance>();
const currentId = ref<string>("");

// 表单数据
const announcementForm = reactive<Announcement>({
  title: "",
  content: "",
  types: "",
  dateTime: new Date(),
  status: "草稿",
});

// 获取公告列表
const getList = async () => {
  const params = { page: page.value, size: size.value };
  const res = await getAnnouncementList({ params });
  announcementList.value = res.data.data;
  total.value = res.data.total;
};

// 显示添加对话框
const showAddDialog = () => {
  // 重置表单
  announcementForm.title = "";
  announcementForm.content = "";
  announcementForm.types = "";
  announcementForm.status = "草稿";
  announcementForm.dateTime = new Date();
  
  isEdit.value = false;
  dialogVisible.value = true;
};

// 显示修改对话框
const showUpDialog = (item: Announcement) => {
  // 填充表单
  announcementForm.title = item.title;
  announcementForm.content = item.content;
  announcementForm.types = item.types;
  announcementForm.status = item.status;
  currentId.value = item._id || "";
  
  isEdit.value = true;
  dialogVisible.value = true;
};

// 添加或更新公告
const add = async () => {
  if (!isEdit.value) {
    // 添加公告
    const res = await addAnnouncement(announcementForm);
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg);
      dialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.data.msg);
    }
  } else {
    // 编辑公告
    const params = {
      _id: currentId.value,
      ...announcementForm
    };
    const res = await updateAnnouncement(params);
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg);
      dialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.data.msg);
    }
  }
};

// 删除公告
const del = async (item: Announcement) => {
  try {
    const res = await deleteAnnouncement({ _id: item._id });
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error: any) {
    console.error('删除公告失败:', error);
    ElMessage.error(error.response?.data?.msg || '删除失败');
  }
};

// 分页处理函数
const handleCurrentChange = (val: number) => {
  page.value = val;
  getList();
};

const handleSizeChange = (val: number) => {
  size.value = val;
  page.value = 1;
  getList();
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
.announcements-container {
  padding: 20px;
}

.page-title {
  font-size: 22px;
  margin-bottom: 20px;
  font-weight: bold;
  color: #333;
}

.actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.add-btn {
  background-color: #e6333e;
  border-color: #e6333e;
  color: white;
  font-weight: 500;
}

.announcement-table {
  margin-bottom: 20px;
  border-radius: 4px;
}

.action-btn {
  margin: 0 3px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.type-tag {
  min-width: 70px;
  text-align: center;
}

:deep(.el-tag--plain.el-tag--danger) {
  background-color: #ffeff0;
  color: #f56c6c;
}

:deep(.el-tag--plain.el-tag--success) {
  background-color: #edf9eb;
  color: #67c23a;
}

:deep(.el-tag--plain.el-tag--info) {
  background-color: #f3f4f6;
  color: #909399;
}

:deep(.el-tag--plain.el-tag--warning) {
  background-color: #fcf5eb;
  color: #e6a23c;
}

/* 分页组件颜色自定义 */
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #e6333e;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #e6333e;
}

:deep(.el-pagination .btn-prev:hover, .el-pagination .btn-next:hover) {
  color: #e6333e;
} 
</style>